﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.DAL;
using Viettel.VOFFICE.DAO.Enums;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class DocInboxController : BaseController
    {
        public DocInboxController() { }
        //
        // GET: /Document/

        /// <summary>
        /// Vào sổ văn bản đến
        /// </summary>
        /// <param name="docModel"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_doc_inbox")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddDocument(DocInboxModel docModel)
        {
            ITransaction transaction = null;
            try
            {
                List<ValidationResult> errors;
                if (docModel.IsValid(out errors))
                {
                    var uow = new UnitOfWork();
                    transaction = uow.BeginTransaction();
                    //Kiểm tra các cấu hình luồng
                    var startNode = uow.NodeRepository.GetStartByFlow(docModel.FlowId);
                    if (null == startNode)
                    {
                        throw new Exception(Resources.Resources.DocInboxNeedStartNode);
                    }
                    if (null == startNode.NodeUsers || startNode.NodeUsers.Count == 0)
                    {
                        throw new Exception(Resources.Resources.DocInboxNeedPeopleInStart);
                    }
                    var book = uow.BookRepository.GetById(docModel.BookId);
                    if (null == book)
                    {
                        throw new Exception(Resources.Resources.DocInboxNeedBook);
                    }
                    var now = DateTime.Now;
                    var creatorId = GetCurentUserId();
                    var docInbox = new DocumentInbox()
                        {
                            Code = docModel.Code,
                            PaperCode = docModel.PaperCode,
                            Abstract = docModel.Abstract,
                            IsPackage = docModel.IsPackage,
                            Status = (byte)DocInboxStatus.Start,
                            SignDate = docModel.SignDate,
                            SignName = docModel.SignName,
                            DocDate = docModel.DocDate,
                            DocTypeId = docModel.DocTypeId,
                            CreatedAt = now,
                            UpdatedAt = now,
                            CreatorId = creatorId,
                            DepartmentIdCreate = docModel.DepartmentIdCreate,
                            Priority = docModel.Priority,
                            Security = docModel.Security,
                            ReceivedType = docModel.ReceivedType,
                            DeadLine = docModel.DeadLine,
                            LeadMessage = docModel.LeadMessage,
                            OuterOfficeIdSent = docModel.OuterOfficeIdSent,
                            NumberOfDoc = docModel.NumberOfDoc,
                            PageOfDoc = docModel.PageOfDoc,
                            CopyFromId = docModel.CopyFromId,
                            Storage = (byte)DocStorage.None,
                            IsReply = docModel.ReplyDocId == null || docModel.ReplyDocId == 0 ? false : docModel.IsReply,
                            ReplyDocId = docModel.ReplyDocId,
                            DocOutboxId = docModel.DocOutboxId,
                            IsActive = true,
                            IsFinished = false,
                        };
                    //bắt đầu tạo lại code
                    uow.DocumentInboxRepository.Insert(docInbox);

                    //Lưu dữ liệu vào bảng documentbook
                    var docBook = new DocumentBook()
                        {
                            BookId = docModel.BookId,
                            DocId = docInbox.Id,
                            Code = docModel.Code,
                            BookNumber = docModel.CurrentNumber,
                            BookType = book.BookType,
                            CreatedAt = now,
                            UpdatedAt = now,
                            CreatorId = creatorId
                        };
                    uow.DocumentBookRepository.Insert(docBook);

                    //file đính kèm
                    if (docModel.UploadedFiles != null && docModel.UploadedFiles.Count > 0)
                    {
                        foreach (var uploadedFile in docModel.UploadedFiles)
                        {
                            if (uploadedFile.Key != null && !string.IsNullOrWhiteSpace(uploadedFile.Key.ToString()))
                            {
                                var path = uploadedFile.Key.ToString();
                                var attach = new Attachment()
                                    {
                                        
                                        ObjectId = docInbox.Id,
                                        ObjectType = (byte)AttachmentType.DocInbox,
                                        FileName = Path.GetFileName(uploadedFile.Value),
                                        FilePath = uploadedFile.Key.ToString(),
                                        DocPath = UtilityHelper.IsDoc(path) ? path : null,
                                        PdfPath = UtilityHelper.IsPdf(path) ? path : null,
                                        ImgPath = UtilityHelper.IsImage(path) ? path : null,
                                        CreatedAt = now,
                                        UpdatedAt = now,
                                        IsDeleted = false,
                                        DeletedById = null,
                                        CreatorId = creatorId
                                    };
                                uow.AttachmentRepository.Insert(attach);
                            }
                        }
                    }

                    //đưa hồ sơ cho người dùng trong luồng
                    var startUsers = startNode.NodeUsers;
                    foreach (var startUser in startUsers)
                    {
                        var traceFlow = new TraceFlow()
                            {
                                FromUserId = creatorId,
                                ToUserId = startUser.UserId,
                                FromNodeId = null,
                                ToNodeId = startUser.NodeId,
                                SubmissionId = null,
                                IsSubmission = false,
                                DocId = docInbox.Id,
                                FlowStatus = (byte)FlowStatus.Start,
                                DocStatus = docInbox.Status,
                                MainExecutor = startUser.MainExecutor,
                                CoExcutor = !startUser.MainExecutor,
                                ComingDate = now,
                                Comment = string.Empty,
                                StillKeep = true,
                                TransferNext = false,
                                TransferBack = false,
                                IsRead = false,
                                UpdatedAt = now,
                                CreatedAt = now
                            };
                        uow.TraceFlowRepository.Insert(traceFlow);
                    }
                    transaction.Commit();
                    return Json(SimplyResponse.ResposeWithId(docInbox.Id));
                }
                else
                {
                    return Json(new JsonResponse() { Status = false, Result = string.Join("<br/>", errors) });
                }
            }
            catch (Exception ex)
            {
                if (null != transaction)
                {
                    transaction.Rollback();
                }
                return Json(SimplyResponse.Response500(ex.Message));
            }
            finally
            {
                if (null != transaction)
                {
                    transaction.Dispose();
                }
            }
        }

        /// <summary>
        /// Cập nhập văn bản đến
        /// </summary>
        /// <param name="docModel"></param>
        /// <returns></returns>
        [HttpPut]
        [ActionName("update_doc_inbox")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateDocument(DocInboxModel docModel)
        {
            try
            {

            }
            catch (Exception)
            {

                throw;
            }
            return null;
        }
    }
}
